import {login,getTokin,logout} from '@/api/user'
import {resetRouter  } from '@/router'
import { getToken, setToken, removeToken} from '@/utils/tokin'
// import createRoutes from '@/utils/creaoutes'
import {asyncRoutes} from '@/router/index.js'

function hasPermission(roles, route) {
  if (route.meta) {
    if(route.meta.Level){
      return true
    }else if(route.meta.id){
      return  (roles.includes(route.meta.id));
    } 
  } else {
    return true
  }
}
export function filterAsyncRoutes(routes, roles) {
  const res = [];
 routes.forEach(route => {
   const tmp = { ...route };
   if(route.hidden){
     res.push(tmp);
   }else{
     if (hasPermission(roles, tmp)) {
         if (tmp.children) {
           tmp.children = filterAsyncRoutes(tmp.children, roles)
         } 
         res.push(tmp)
     }
   }
 })
 return res
}
// 恢复默认的
const getDefaultState = () => {
    return {
      token:getToken('FcLogin'),
      roles:'',  
      perms:'',
      username:'',
      roters:'',
      roterslist:''
    }
  }
const state = getDefaultState()
const mutations = {
    RESET_STATE: (state) => {
      Object.assign(state, getDefaultState())
    },
    SET_USERPERMS: (state, perms) => { //  用户信息按钮权限
      state.perms = perms;
    },
    SET_USERNAME: (state, username) => { //  用户信息 
      state.username = username;
    },
    SET_USERINFOR: (state, roles) => { //  用户路由信息
      state.roles = roles;
    },
    SET_ROUTERS: (state, roters) => { //  用户路由信息
      state.roters = roters;
    },
    SET_ROUTERSLIST: (state, roterslist) => { //  用户路由信息
      state.roterslist = roterslist;
    },
    SET_TOKEN: (state, token) => {     // token
      state.token = token
    },
  }
  const actions = {
    // // user login   获取页面数据
    generateRoutes({ commit },roles){
      return new Promise(resolve => {
        let accessedRoutes
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        let array=[];
        accessedRoutes.forEach(item=>{
          if(item.hidden){
            array.push(item)
          }else{
            if(item.children){
              if(item.children.length>=1){
                array.push(item)
              }
            }
          }
        })
        commit('SET_ROUTERS', array);
        commit('SET_ROUTERSLIST', asyncRoutes);
        resolve(accessedRoutes)
      })
    },
    login({ commit},data) {
      return new Promise((resolve, reject) => {
        login(data).then(response => {
          console.log(response)
          if(response.data.code==1){
            commit('SET_USERNAME',{ "nickname":data.user ,"avatarstr":'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'});
          }else{
            removeToken()  
          }
          resolve(response.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    //获取用户信息
    getTokin({commit},token){
      return new Promise((resolve, reject) => {
        console.log(token)
        getTokin(token).then(response => {
          console.log(response)
          const { data } = response.data
          commit('SET_TOKEN', data.token)
          setToken( data.token)  
          if (!data) {
            return reject('验证失败，请重新登录。')
          }
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // user logout
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        logout({commit}).then(() => {
          // commit('RESET_STATE')
          // commit('SET_USERPERMS', '')
          commit('SET_USERNAME', '')
          commit('SET_ROUTERS', '')
          resetRouter()
          removeToken('FcLogin') // must remove  token  first;

          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
  export default {
    namespaced: true,
    state,
    mutations,
    actions
  }
  